package com.elong.android.specialhouse.base;

import android.os.Bundle;

import com.alibaba.fastjson.JSONObject;
import com.dp.android.elong.crash.constants.JSONConstants;
import com.elong.android.specialhouse.R;
import com.elong.android.specialhouse.dialogutil.HttpErrorDialog;
import com.elong.android.specialhouse.dialogutil.HttpLoadingDialog;
import com.elong.android.specialhouse.dialogutil.HttpTimeoutDialog;
import com.elong.android.specialhouse.dialogutil.IHttpErrorConfirmListener;
import com.elong.android.specialhouse.utils.StringUtils;
import com.elong.android.specialhouse.utils.Utils;
import com.elong.framework.net.error.NetFrameworkError;
import com.elong.framework.netmid.ElongRequest;
import com.elong.framework.netmid.RequestExecutor;
import com.elong.framework.netmid.api.IHusky;
import com.elong.framework.netmid.request.RequestOption;
import com.elong.framework.netmid.response.BaseResponse;
import com.elong.framework.netmid.response.IResponse;
import com.elong.framework.netmid.response.IResponseCallback;
import com.elong.framework.netmid.response.StringResponse;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @author kaiqi.li
 * @Description
 * @date 2015/10/20 9:53
 */
public abstract class BaseVolleyFragmentActivity<T extends IResponse<?>> extends BaseFragementActivity implements IResponseCallback,
        IHttpErrorConfirmListener {

    private List<ElongRequest> runningList = new ArrayList<ElongRequest>();
    private List<ElongRequest> waitingList = new ArrayList<ElongRequest>();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initDialog();
    }

    /******************************************************************
     * Dialog控制
     *****************************************************************/
    private HttpLoadingDialog loadingDialog;
    private HttpTimeoutDialog timeoutDialog;

    private void initDialog() {
        loadingDialog = new HttpLoadingDialog(this);
        timeoutDialog = new HttpTimeoutDialog(this);
    }

    /**
     * loading/超时/错误对话框 绑定 Request
     *
     * @param request
     */
    public void bindDialogRequest(final ElongRequest request) {
        loadingDialog.bindRequest(request);
        timeoutDialog.bindRequest(request);
        timeoutDialog.bindHttpErrorConfirmListener(this);
    }

    /**
     * 显示loading框
     */
    public void showLoading() {
        if (loadingDialog.isShowing())
            return;

        dismissAllDialog();
        loadingDialog.show();
    }

    /**
     * 显示超时框
     */
    public void showTimeout() {
        if (timeoutDialog.isShowing())
            return;

        dismissAllDialog();
        timeoutDialog.show();
    }

    /**
     * 显示http错误框
     */
    public void showError(boolean show) {
    }

    public void dismissAllDialog() {
        if (loadingDialog.isShowing())
            loadingDialog.dismiss();

        if (timeoutDialog.isShowing())
            timeoutDialog.dismiss();
    }

    /**
     * Http错误框点击确认时的操作
     */
    @Override
    public void onHttpErrorConfirm(ElongRequest request) {
        // TODO Auto-generated method stub

    }

    /**
     * Http超时框点击继续的操作
     */
    @Override
    public void onHttpContinue(ElongRequest request) {
        showLoading();
    }

    public void showTaskError(IResponse t) {
        if (t != null) {
            JSONObject obj = (JSONObject) JSONObject.parse(((StringResponse) t).getContent());
            if (obj == null) {
                return;
            }
            String errorMessage = "";
            if (obj.getBooleanValue("IsError")) {
                errorMessage = obj.getString("ErrorMessage");
                if (StringUtils.isEmpty(errorMessage)) {
                    errorMessage = "网络错误，请稍后再试！";
                }
                DialogUtils.showInfo(this, null, errorMessage);
            }
        }
    }

    /******************************************************************
     * BaseNetActivity提供给Activity的Http请求调用入口
     *
     *****************************************************************/

    /**
     *
     * @param option
     * @param beanClass
     * @return
     */
    public ElongRequest requestHttp(RequestOption option, Class<? extends IResponse<?>> beanClass) {
        return requestHttp(option, null, beanClass, true);
    }

    /**
     *
     * @param option
     * @param husky
     * @param beanClass
     * @return
     */
    public ElongRequest requestHttp(RequestOption option, IHusky husky, Class<? extends IResponse<?>> beanClass) {
        return requestHttp(option, husky, beanClass, false);
    }

    public ElongRequest requestHttp(RequestOption option, IHusky husky, Class<? extends IResponse<?>> beanClass, boolean dialogFlag) {
        if (beanClass != null) {
            option.setBeanClass(beanClass);
        } else {
            option.setBeanClass(BaseResponse.class);
        }
        if (husky != null) {
            option.setHusky(husky);
        }
        ElongRequest request = null;
        try {
            request = RequestExecutor.executeRequest(option.process(), this);
        } catch (Exception e) {
            e.printStackTrace();
        }
        request.setShowDialog(dialogFlag);
        runningList.add(request);

        return request;
    }

    /******************************************************************
     * IRequest生命周期回调
     *****************************************************************/
    @Override
    public void onTaskReady(ElongRequest request) {
        if (request.isShowDialog()) {
            bindDialogRequest(request);
            showLoading();
        }
    }

    @Override
    public void onTaskDoing(ElongRequest request) {

    }

    @Override
    public void onTaskPost(ElongRequest request, IResponse<?> t) {
        if (request.isShowDialog()) {
            dismissAllDialog();
        }
//        showTaskError(t);
    }


    @Override
    public void onTaskCancel(ElongRequest request) {

    }

    @Override
    public void onTaskTimeoutMessage(ElongRequest request) {
        if (request.isShowDialog()) {
            showTimeout();
        }

    }

    /**
     * 网络不可用时回调
     * @param request
     * @param ex
     */
    @Override
    public void onTaskError(ElongRequest request, NetFrameworkError ex) {
        if (request.isShowDialog()) {
            dismissAllDialog();
        }
        HttpErrorDialog.ShowConfirm(this, request, getString(R.string.network_unavailable), this);
    }


    /******************************************************************
     * Activity生命周期管理当前运行http任务 页面销毁时退出所有非业务即时任务 页面到后台暂停所有队列任务
     *****************************************************************/

    @Override
    protected void onResume() {
        for (ElongRequest request : waitingList) {
            request.retry();
            runningList.add(request);
        }
        waitingList.clear();
        super.onResume();
    }

    @Override
    protected void onPause() {
        Iterator<ElongRequest> iterator = runningList.iterator();
        while (iterator.hasNext()) {
            ElongRequest request = iterator.next();
            // 日志后台任务不会受到页面暂停影响
            if (request.getRequestOption().getQueneLev() == RequestOption.QUEUE_LEVEL_WATCH) {
                continue;
            }

            // 不处理已经执行完成的任务
            if (!request.isProcess()) {
                continue;
            }

            // 任务在队列之中则取消任务！！！等待进入页面时再次添加。
            if (!request.isInNetworkProcess()) {
                request.cancel();
                iterator.remove();
                waitingList.add(request);
            }
        }
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        for (ElongRequest request : runningList) {
            // 日志后台任务不会受到页面销毁影响
            if (request.getRequestOption().getQueneLev() == RequestOption.QUEUE_LEVEL_WATCH) {
                continue;
            }

            // 不处理已经执行完成的任务
            if (!request.isProcess()) {
                continue;
            }

            request.cancel();
        }

        for (ElongRequest request : waitingList) {
            if (request.getRequestOption().getQueneLev() == RequestOption.QUEUE_LEVEL_WATCH) {
                continue;
            }

            request.cancel();
        }
        dismissAllDialog();
        super.onDestroy();
    }

    /**
     * 网络响应结果的共性处理
     *
     * @return 处理了共性错误，返回true；否则返回false。
     */
    protected boolean handleIsError(ElongRequest req, JSONObject json) {
        if (req == null || json == null) {
            onTaskError(req, new NetFrameworkError("返回数据为空", -1));
            return true;
        }
        boolean isError = json.getBooleanValue("IsError");
//		String errMsg = json.getString("ErrorMessage");
        if (isError) {
            //session过期
//            if (isLoginForSessionTimeout(json)) {
//                loginForSessionTimeout();
//                return true;
//            }
            // 静默超时
            // if (isNoLoginForSessionTimeout(json)) {
            // }
            //登录需要验证码
//            if (isNeedVerifyCode(json)) {
//                showInputVerifyCodeWindow(json);
//                return true;
//            }
//			onTaskError(req, new NetFrameworkError(errMsg, -1));
            handleServerIsError(json);
            return true;
        }
        return false;
    }

    /**
     * @param
     * @return void
     * @throws
     * @Title: handleServerIsError
     * @Description: 处理服务器返回的iserror = true
     */
    protected void handleServerIsError(JSONObject response) {
        if (response == null) {
            return;
        }
        boolean succeed = !response.getBooleanValue(JSONConstants.ATTR_ISERROR);
        if (!succeed) {
//            if (isLoginForSessionTimeout(response)) {
//                loginForSessionTimeout();
//            } else if (isNoLoginForSessionTimeout(response)) {
//            } else if (isNeedVerifyCode(response)) {
//                showInputVerifyCodeWindow(response);
//            }
            String errorMessage = response.getString(JSONConstants.ATTR_ERRORMESSAGE);
            if (Utils.isEmptyString(errorMessage)) {
                errorMessage = getString(R.string.unknown_error);
            }
            DialogUtils.showInfo(this, null, errorMessage);

        }
    }
}
